package com.diandian.backend.client.service;

import com.alibaba.fastjson.JSON;
import com.diandian.backend.client.constants.ClientConstant;
import com.diandian.backend.client.dto.ClientInfoDetailParamDTO;
import com.diandian.backend.client.dto.ClientPermissionCacheDataDTO;
import com.diandian.backend.client.resp.ClientInfoDetailResp;
import com.diandian.backend.client.resp.ClientSettingListResp;
import com.diandian.base.boot.starter.exception.DefaultException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ClientService {

    private static final Logger logger = LoggerFactory.getLogger(ClientService.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ClientInfoService clientInfoService;

    @Autowired
    private ClientPermissionService clientPermissionService;

    @Autowired
    private ClientMeiTuanShanGouStoreService clientMeiTuanShanGouStoreService;

    @Autowired
    private ClientSettingService clientSettingService;

    /**
     * 手动缓存客户端权限信息
     *
     *      "clientKey": {
     *          "clientSecret":"redisTemplate",
     *          "status": "status",
     *          "startTime":"yyyy-MM-dd HH:mm:ss",
     *          "endTime":"yyyy-MM-dd HH:mm:ss"，
     *          “cmds”:[
     *              "cmd1",
     *              "cmd2"
     *          ]
     *      }
     *      首先校验信息:
     *      1. 校验clientId和clientSecret是否正确
     *      2. 校验client是否为启用状态且在有效期内
     *
     *
     * @param clientId
     */
    public void manualCache(String clientId) {

        // 从数据库查询权限数据
        ClientPermissionCacheDataDTO dbPermissionDTO = getPermissionCacheData(clientId);

//        String status = dbPermissionDTO.getStatus();
//        if(ClientConstant.PERMISSION_STATUS_DISABLE.equals(status)){
//            throw new DefaultException("客户端已禁用");
//        }
//
//        Date startTime = dbPermissionDTO.getStartTime();
//        if(new Date().before(startTime)){
//            throw new DefaultException("客户端暂未生效");
//        }
//        Date endTime = dbPermissionDTO.getEndTime();
//        if(new Date().after(endTime)){
//            throw new DefaultException("客户端已失效");
//        }

        // 缓存权限数据
        String permissionStr = JSON.toJSONString(dbPermissionDTO);
        redisTemplate.opsForValue().set(ClientConstant.CLIENT_PERMISSION_CACHE_PREFIX + dbPermissionDTO.getClientKey(), permissionStr);

        logger.info("clientId {} 的权限缓存完成，权限信息：{}", clientId, permissionStr);
    }

    /**
     * 删除缓存
     * @param clientKey
     */
    public void clearCache(String clientKey) {
        redisTemplate.delete(ClientConstant.CLIENT_PERMISSION_CACHE_PREFIX + clientKey);
    }

    /**
     * 从数据库中查询权限信息
     * @param clientId
     * @return
     */
    private ClientPermissionCacheDataDTO getPermissionCacheData(String clientId) {

        // 查询客户端信息
        ClientInfoDetailParamDTO queryParamDTO = new ClientInfoDetailParamDTO();
        queryParamDTO.setClientId(clientId);
        ClientInfoDetailResp clientInfoDTO = clientInfoService.getDetail(queryParamDTO);
        if(clientInfoDTO == null){
            throw new DefaultException("未找到此客户端");
        }

        ClientPermissionCacheDataDTO resultDTO = new ClientPermissionCacheDataDTO();
        resultDTO.setClientId(clientInfoDTO.getClientId());
        resultDTO.setClientKey(clientInfoDTO.getClientKey());
        resultDTO.setClientSecret(clientInfoDTO.getClientSecret());
        resultDTO.setStatus(clientInfoDTO.getStatus());
        resultDTO.setStartTime(clientInfoDTO.getStartTime());
        resultDTO.setEndTime(clientInfoDTO.getEndTime());

        // 查询权限信息
        List<String> cmdList = clientPermissionService.getPermissions(clientId);
        if(clientInfoDTO == null){
            cmdList = new ArrayList<>();
        }
        resultDTO.setCmds(cmdList);

        // 设置美团闪购门店编码集合
        List<String> meiTuanShanGouStoreCodeList = clientMeiTuanShanGouStoreService.getStoreCodeListByClientId(clientId);
        if(meiTuanShanGouStoreCodeList == null){
            meiTuanShanGouStoreCodeList = new ArrayList<>();
        }
        resultDTO.setMeiTuanShanGouStoreCodes(meiTuanShanGouStoreCodeList);

        // 设置配置信息集
        List<ClientSettingListResp> settingList = clientSettingService.getList(clientId, null);
        if(settingList == null){
            settingList = new ArrayList<>();
        }
        /**
         * tempMap结构如下：
         * {
         *     "type1":{
         *         "key1": "value1",
         *         "key2":"value2"
         *     },
         *     "type2":{
         *         "key1": "value1",
         *         "key2":"value2"
         *     }
         * }
         */
        Map<String, Map<String, String>> settingMap = new HashMap();
        for (int i = 0; i < settingList.size(); i++) {
            String type = settingList.get(i).getType();
            String paramKey = settingList.get(i).getParamKey();
            String paramValue = settingList.get(i).getParamValue();

            if(settingMap.get(type) == null){
                Map<String, String> innerMap = new HashMap<>();
                innerMap.put(paramKey, paramValue);
                settingMap.put(type, innerMap);
                continue;
            }

            Map<String, String> innerMap = settingMap.get(type);
            innerMap.put(paramKey, paramValue);
        }
        resultDTO.setSetting(settingMap);

        return resultDTO;
    }
}
